import React, { useEffect, useState } from 'react';
import { Typography, message, Modal, Space, Button } from 'antd';
import { ExclamationCircleOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { SearchTable } from '../../components/common/Table/SearchTable';
import { MemberModal } from '../../components/common/Modal/MemberModal';
import { ConfirmModal } from '../../components/common/Modal/ConfirmModal';
import { useMember } from '../../hooks/useMember';
import type { Member, CreateMemberRequest, UpdateMemberRequest } from '../../store/slices/memberSlice';

const { Title } = Typography;

interface MemberFormValues {
  name: string;
  department: string;
  email: string;
  phone: string;
  status: 'active' | 'inactive';
}

export const MemberList: React.FC = () => {
  const {
    members,
    loading,
    createMember,
    modifyMember,
    removeMember,
    refreshMembers,
    initMembers
  } = useMember();

  const [searchValue, setSearchValue] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingMember, setEditingMember] = useState<Member | null>(null);
  const [modalLoading, setModalLoading] = useState(false);

  // ConfirmModal 相关状态
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [deletingMember, setDeletingMember] = useState<{ id: number, name: string } | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // 初始化数据
  useEffect(() => {
    initMembers();
  }, [initMembers]);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 150,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <span style={{ color: status === 'active' ? '#52c41a' : '#ff4d4f' }}>
          {status === 'active' ? '活跃' : '禁用'}
        </span>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Member) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id, record.name)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索处理
  const handleSearch = (value: string) => {
    setSearchValue(value);
  };

  // 打开新增弹窗
  const handleAdd = () => {
    setEditingMember(null);
    setIsModalVisible(true);
  };

  // 打开编辑弹窗
  const handleEdit = (member: Member) => {
    setEditingMember(member);
    setIsModalVisible(true);
  };

  // 提交表单（新增/编辑）
  const handleFormSubmit = async (values: MemberFormValues) => {
    setModalLoading(true);
    try {
      if (editingMember) {
        // 编辑成员
        const updateData: UpdateMemberRequest = {
          id: editingMember.id,
          ...values
        };
        await modifyMember(updateData);
        message.success('成员更新成功');
      } else {
        // 新增成员
        const createData: CreateMemberRequest = {
          ...values
        };
        await createMember(createData);
        message.success('成员添加成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      message.error(editingMember ? '更新成员失败' : '添加成员失败');
      throw error;
    } finally {
      setModalLoading(false);
    }
  };

  // 删除成员 - 打开 ConfirmModal
  const handleDelete = (memberId: number, memberName: string) => {
    setDeletingMember({ id: memberId, name: memberName });
    setConfirmModalVisible(true);
  };

  // 确认删除
  const handleDeleteConfirm = async () => {
    if (!deletingMember) return;

    setDeleteLoading(true);
    try {
      await removeMember(deletingMember.id);
      message.success('成员删除成功');
      setConfirmModalVisible(false);
      setDeletingMember(null);
    } catch (error) {
      message.error('删除成员失败');
    } finally {
      setDeleteLoading(false);
    }
  };

  // 取消删除
  const handleDeleteCancel = () => {
    setConfirmModalVisible(false);
    setDeletingMember(null);
    message.info('取消删除操作');
  };

  // 刷新列表
  const handleRefresh = () => {
    refreshMembers();
    message.info('刷新成员列表');
  };

  // 取消表单
  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingMember(null);
  };

  // 根据搜索值过滤数据
  const filteredData = members.filter(member =>
    member.name.toLowerCase().includes(searchValue.toLowerCase()) ||
    member.department?.toLowerCase().includes(searchValue.toLowerCase()) ||
    member.email?.toLowerCase().includes(searchValue.toLowerCase()) ||
    member.phone?.includes(searchValue)
  );

  return (
    <div>
      <Title level={2}>成员管理</Title>

      <SearchTable<Member>
        tableTitle="成员列表"
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        onSearch={handleSearch}
        onAdd={handleAdd}
        onRefresh={handleRefresh}
        searchPlaceholder="搜索成员姓名、部门、邮箱或电话..."
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
        }}
        loading={loading}
      />

      {/* 成员编辑/新增弹窗 */}
      <MemberModal
        visible={isModalVisible}
        editingMember={editingMember}
        onSubmit={handleFormSubmit}
        onCancel={handleCancel}
        loading={modalLoading}
      />

      {/* 删除确认框 - 使用 ConfirmModal */}
      <ConfirmModal
        open={confirmModalVisible}
        title="确认删除"
        content={
          <div>
            <p>确定要删除成员 <strong>"{deletingMember?.name}"</strong> 吗？</p>
            <p style={{ color: '#ff4d4f' }}>此操作不可恢复，请谨慎操作！</p>
          </div>
        }
        onConfirm={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        type="danger"
        confirmText="删除"
        cancelText="取消"
        loading={deleteLoading}
      />
    </div>
  );
};

export default MemberList;